package com.example.demo.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author: LKP
 * @create: 2020/11/26
 * @Description: 接口的日志切面
 * @FileName: WebLogAspect
 * @History:
 * @自定义内容：
 */
@Aspect
@Slf4j
@Component
public class WebLogAspect {

    @Pointcut("execution(* com.example.demo.controller..*.*(..))")
    public void webLogAspect() {
    }

    @Before("webLogAspect()")
    public void doBefore(JoinPoint joinPoint) {
        //接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        log.info("---------------------- Start ----------------------");
        log.info("Cookie: " + request.getHeader("Cookie"));
        log.info(request.getMethod() + " => " + request.getRequestURL().toString());
        log.info("IP: " + request.getRemoteAddr());
        log.info("CLASS_METHOD: "
                + joinPoint.getSignature().getDeclaringTypeName()
                + "."
                + joinPoint.getSignature().getName());
        log.info("ARGS: " + Arrays.toString(joinPoint.getArgs()));
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>");
    }

    @AfterReturning(returning = "ret", pointcut = "webLogAspect()")
    public void doAfterReturning(Object ret) {
        // 关闭:  返回前进行内容结果日志输出
        log.info("RESPONSE：" + ret);
        log.info("----------------------- End -----------------------\n");
    }

}
